package game.engine.base.anim.composition

import game.engine.base.Node
import game.engine.base.anim.Tween
import game.engine.base.anim.cloneTween

//  并行
class Parallel(vararg tweens: Tween): Tween(){

    val lst = ArrayList<Tween>()
    var firstExecute = false

    init {
        tweens.forEach { lst.add(it) }
    }

    override fun initialize(node: Node) {
        lst.forEach {
            it.target = node
            it.initialize(node)
        }
    }

    override fun execute(dt: Float) {
        val node = target!!
        if (!firstExecute) {
            initialize(node)
            firstExecute = true
        }

        for (i in lst.indices){
            val tween = lst[i]
            tween.execute(dt)
            if (tween.end){
                if (tween.nextTween == null){
                    tween.allEnd = true
                }else{
                    lst[i] = tween.nextTween!!
                    lst[i].target = node
                }
            }
        }

        // 删除已经执行完毕的
        val iter = lst.iterator()
        while (iter.hasNext()){
            val tween = iter.next()
            if (tween.allEnd){
                iter.remove()
            }
        }

        // 什么时候全部执行完毕?
        if (lst.size < 1){
            end = true
        }
    }

    override fun clone(): Tween {
        val arr = Array<Tween>(lst.size){ idx->
            lst[idx].cloneTween()
        }
        return Parallel(*arr)
    }
}